import React, { startTransition, useState } from 'react'
import { NavBar, Switch, Button } from 'antd-mobile'
import { useLocation, useNavigate } from 'react-router-dom'
import '../css/addaddress.css'
import axios from 'axios'


export default function Addaddress() {
  const location = useLocation();
  
  const navigate = useNavigate();
  const [item, setItem] = useState(location.state||{
    name: '',
    phone: '',
    city: '',
    address: '',
    isDefault: false
  })
  const right = (
    <div style={{ fontSize: 24 }}>
      <span style={{ color: '#c1ab96', fontSize: '1.5rem' }} onClick={() => {
        let data = { _id: item._id, name: item.name, phone: item.phone, city: item.city +' '+ item.address, isDefault: item.isDefault, u_id: JSON.parse(sessionStorage.getItem('users'))._id }
        axios.post('cxb/addaddress', data).then(res => {
          if (res.data.code === 200) {
            startTransition(() => {
              navigate('/address')
            })
          }
        })
      }}>保存</span>
    </div>
  )
  const back = () => {
    startTransition(() => {
      navigate('/address')
    })
  }
  return (
    <div>
      <div className='cxb_address_top'>
        <NavBar right={right} onBack={back}>新增收货地址</NavBar>
      </div>
      <div className="cxb_addaddress_content">
        <li>
          <label>收货人</label>
          <input type='text' placeholder='请填写收货人姓名' value={item.name} onChange={e => setItem({ ...item, name: e.target.value })}></input>
        </li>
        <li>
          <label>手机号码</label>
          <input type='text' placeholder='' value={item.phone} onChange={e => setItem({ ...item, phone: e.target.value })}></input>
        </li>
        <li>
          <label>所在地区</label>
          <input type='text' placeholder='省市区县、乡镇等' value={item.city} onChange={e => setItem({ ...item, city: e.target.value })}></input>
        </li>
        <li>
          <label>详细地址</label>
          <input type='text' placeholder='街道、楼牌号等' value={item.address} onChange={(e) => setItem({ ...item, address: e.target.value })}></input>
        </li>
        <li>
          <label style={{ width: '30%' }}>设置默认地址</label>
          <Switch checked={item.isDefault} onChange={(e) => setItem({ ...item, isDefault: e })} />
        </li>
      </div>
      {location.state&&<Button onClick={()=>{
        axios.delete('/cxb/deladdress?_id='+location.state._id).then(res=>{
          if(res.data.code===200){
            startTransition(()=>{
              navigate('/address')
            })
          }
        })
      }} block color='danger' style={{position:'fixed',bottom:'0',borderRadius:'2rem'}}>删除收货地址</Button>}
    </div>
  )
}
